#!/usr/bin/env python3
# Copyright (c) 2022 maminjie <canpool@163.com>
# SPDX-License-Identifier: MulanPSL-2.0


import os
import sys
import argparse
import configparser


def parse_command_line():
    params = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter)
    params.add_argument("-c", "--command", type=str, choices=['get', 'set'], required=True,
                        help="The subcommand, as follows:\n"
                             "  get - Get a key value for a given section\n"
                             "  set - Set a key, should input value\n")
    params.add_argument("-f", "--file", type=str, required=True,
                        help="The config file")
    params.add_argument("-s", "--section", type=str, required=True,
                        help="The section of config file")
    params.add_argument("-k", "--key", type=str, required=True,
                        help="The key of section")
    params.add_argument("-v", "--value", type=str, default="",
                        help="The value of key")
    args = params.parse_args()
    return args


def conf_get(file, section, key):
    if os.path.isfile(file):
        conf = configparser.ConfigParser()
        conf.read(file)
        if conf.has_section(section):
            value = conf.get(section, key)
            print(value)


def conf_set(file, section, key, value):
    if os.path.isfile(file):
        conf = configparser.ConfigParser()
        conf.read(file)
        if not conf.has_section(section):
            conf.add_section(section)
        conf.set(section, key, value)
        conf.write(open(file, "w"))


def do_main(args):
    if args.command == "set":
        if not args.value:
            print("should input value")
            sys.exit(1)
        conf_set(args.file, args.section, args.key, args.value)
    elif args.command == "get":
        return conf_get(args.file, args.section, args.key)


def main():
    args = parse_command_line()
    do_main(args)


if __name__ == "__main__":
    main()
